package com.kwedding.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.management.InstanceAlreadyExistsException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

public class MessageUtil extends LoggerParent {

    private static String projectName = null;

    public static boolean sendMessage(String phoneNumber, MessageEnmu messageEnmu, LinkedHashMap<String, Object> map)
            throws UnsupportedEncodingException {


        String accesskey = "BFxHE6ouc68d1X1Z"; // 用户开发key
        String accessSecret = "aTKSbiAheKimvTNyTihZOiYlN7AD7mpI"; // 用户开发秘钥
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/send");
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        projectName = "Artiz";
        String sign = null;
        switch (projectName) {
            case "Artiz":
                sign = "2130";
                projectName = "Kwedding";
                break;
            case "Galleria":
                sign = "2132";
                break;
            case "Kwedding":
                sign = "2130";
                break;

            default:
                sign = "2130";
                break;
        }

        // 组装个性短信内容
//        JSONObject jsonObj = new JSONObject();
//        jsonObj.put(phoneNumber, messageConetnt);
        String messageConetnt = linkedHashMap2String(map);
        if (MessageEnmu.CODE.equals(messageEnmu) || MessageEnmu.EXCHANGE.equals(messageEnmu)) {
            messageConetnt = "【" + projectName + "】##" + messageConetnt;
        }
        // （示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
        NameValuePair[] data = {new NameValuePair("accesskey", accesskey), new NameValuePair("secret", accessSecret),
                new NameValuePair("sign", sign), new NameValuePair("templateId", messageEnmu.getTemplateChuangRui()),
                new NameValuePair("mobile", phoneNumber),
                new NameValuePair("content", URLEncoder.encode(messageConetnt, "utf-8"))};
        postMethod.setRequestBody(data);
        int statusCode;
        try {
            statusCode = httpClient.executeMethod(postMethod);
            if (statusCode == 200) {
                String result = postMethod.getResponseBodyAsString();
                System.out.println(result);
                JSONObject jsonObject = new JSONObject(result);
                String code = jsonObject.getString("code");
                if (code.equals("0")) {
                    return true;
                } else {
                    // 如果失败请求阿里大于
                    return MessageALiDaYuMessageUtil.sendMessage(messageEnmu.getTemplateAli(), phoneNumber, map);
                }
            } else {
                // 如果失败请求阿里大于
                return MessageALiDaYuMessageUtil.sendMessage(messageEnmu.getTemplateAli(), phoneNumber, map);
            }
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

   /* public static boolean sendExchangeMessage(String phoneNumber, String messageConetnt,
                                              TB_RequestMapper tb_RequestMapper) throws UnsupportedEncodingException {

        if (projectName == null) {
            if (tb_RequestMapper == null) {
                return false;
            }
            TB_Request tb_Request = tb_RequestMapper.selectOne();
            String[] requestUrls = tb_Request.getRequestUrl().split("/");
            projectName = requestUrls[1].substring(0, 1).toUpperCase() + requestUrls[1].substring(1);
        }

        String accesskey = "BFxHE6ouc68d1X1Z"; // 用户开发key
        String accessSecret = "aTKSbiAheKimvTNyTihZOiYlN7AD7mpI"; // 用户开发秘钥
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/send");
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        String sign = null;
        switch (projectName) {
            case "Artiz":
                sign = "2130";
                projectName = "Kwedding";
                break;
            case "Galleria":
                sign = "2132";
                break;
            case "Kwedding":
                sign = "2130";
                break;

            default:
                sign = "2130";
                break;
        }

        // 组装个性短信内容
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(phoneNumber, messageConetnt);
        // （示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
        NameValuePair[] data = {new NameValuePair("accesskey", accesskey), new NameValuePair("secret", accessSecret),
                new NameValuePair("sign", sign), new NameValuePair("templateId", "4102"),
                new NameValuePair("mobile", phoneNumber),
                new NameValuePair("content", URLEncoder.encode("【" + projectName + "】##" + messageConetnt, "utf-8"))};
        postMethod.setRequestBody(data);
        int statusCode;
        try {
            statusCode = httpClient.executeMethod(postMethod);
            if (statusCode == 200) {
                String result = postMethod.getResponseBodyAsString();
                System.out.println(result);
                JSONObject jsonObject = new JSONObject(result);
                String code = jsonObject.getString("code");
                if (code.equals("0")) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    *//**
     * 发送预约门店短信
     *
     * @param phoneNumber
     * @param messageConetnt
     * @param tb_RequestMapper
     * @return
     * @throws UnsupportedEncodingException
     *//*
    public static boolean sendSubscribeBrandMessage(String phoneNumber, String messageConetnt,
                                                    TB_RequestMapper tb_RequestMapper) throws UnsupportedEncodingException {

        if (projectName == null) {
            if (tb_RequestMapper == null) {
                return false;
            }
            TB_Request tb_Request = tb_RequestMapper.selectOne();
            String[] requestUrls = tb_Request.getRequestUrl().split("/");
            projectName = requestUrls[1].substring(0, 1).toUpperCase() + requestUrls[1].substring(1);
        }

        String accesskey = "BFxHE6ouc68d1X1Z"; // 用户开发key
        String accessSecret = "aTKSbiAheKimvTNyTihZOiYlN7AD7mpI"; // 用户开发秘钥
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/send");
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        String sign = null;
        switch (projectName) {
            case "Artiz":
                sign = "2130";
                projectName = "Kwedding";
                break;
            case "Galleria":
                sign = "2132";
                break;
            case "Kwedding":
                sign = "2130";
                break;

            default:
                sign = "2130";
                break;
        }

        // 组装个性短信内容
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(phoneNumber, messageConetnt);
        // （示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
        NameValuePair[] data = {new NameValuePair("accesskey", accesskey), new NameValuePair("secret", accessSecret),
                new NameValuePair("sign", sign), new NameValuePair("templateId", "6394"),
                new NameValuePair("mobile", phoneNumber),
                new NameValuePair("content", URLEncoder.encode("【" + projectName + "】" + messageConetnt, "utf-8"))};
        postMethod.setRequestBody(data);
        int statusCode;
        try {
            statusCode = httpClient.executeMethod(postMethod);
            if (statusCode == 200) {
                String result = postMethod.getResponseBodyAsString();
                System.out.println(result);
                JSONObject jsonObject = new JSONObject(result);
                String code = jsonObject.getString("code");

                if (code.equals("0")) {
                    return true;
                } else {
                    return false;
                }

            } else {
                return false;
            }
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    *//**
     * 预约商品短信
     *
     * @param phoneNumber
     * @param messageConetnt
     * @param tb_RequestMapper
     * @return
     * @throws UnsupportedEncodingException
     *//*
    public static boolean sendSubscribeMessage(String phoneNumber, String messageConetnt,
                                               TB_RequestMapper tb_RequestMapper) throws UnsupportedEncodingException {

        if (projectName == null) {
            if (tb_RequestMapper == null) {
                return false;
            }
            TB_Request tb_Request = tb_RequestMapper.selectOne();
            String[] requestUrls = tb_Request.getRequestUrl().split("/");
            projectName = requestUrls[1].substring(0, 1).toUpperCase() + requestUrls[1].substring(1);
        }

        String accesskey = "BFxHE6ouc68d1X1Z"; // 用户开发key
        String accessSecret = "aTKSbiAheKimvTNyTihZOiYlN7AD7mpI"; // 用户开发秘钥
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/send");
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        String sign = null;
        switch (projectName) {
            case "Artiz":
                sign = "2130";
                projectName = "Kwedding";
                break;
            case "Galleria":
                sign = "2132";
                break;
            case "Kwedding":
                sign = "2130";
                break;

            default:
                sign = "2130";
                break;
        }

        // 组装个性短信内容
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(phoneNumber, messageConetnt);
        // （示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
        NameValuePair[] data = {new NameValuePair("accesskey", accesskey), new NameValuePair("secret", accessSecret),
                new NameValuePair("sign", sign), new NameValuePair("templateId", "6396"),
                new NameValuePair("mobile", phoneNumber),
                new NameValuePair("content", URLEncoder.encode("【" + projectName + "】" + messageConetnt, "utf-8"))};
        postMethod.setRequestBody(data);
        int statusCode;
        try {
            statusCode = httpClient.executeMethod(postMethod);
            if (statusCode == 200) {
                String result = postMethod.getResponseBodyAsString();
                System.out.println(result);
                JSONObject jsonObject = new JSONObject(result);
                String code = jsonObject.getString("code");
                if (code.equals("0")) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
*/

    /**
     * LinkedHashMap转换成创瑞云短信平台需要的格式
     * LinkedHashMap为阿里大于短信平台需要的格式
     *
     * @param map
     * @return
     */
    private static String linkedHashMap2String(LinkedHashMap<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return "";
        }
        StringBuffer stringBuffer = new StringBuffer();
        Set<String> keySet = map.keySet();

        LinkedHashMap<String, Object> mapWith20 = new LinkedHashMap<>();


        int index = 1;
        // 判断是否有超过20个的变量
        boolean hasUpTo20 = false;
        for (String string : keySet) {
            String value = (String) map.get(string);
            // 判断长度是否超过20
            if (value.length() > 20) {
                // 超过20
                stringBuffer.append(value.substring(0, 20)).append("##").append(value.substring(20, value.length())).append("##");
                mapWith20.put(string, value.substring(0, 20));
                mapWith20.put(string + "1", value.substring(20, value.length()));
                hasUpTo20 = true;
            } else {
                // 不超过20
                stringBuffer.append(map.get(string)).append("##");
                mapWith20.put(string, value);
                mapWith20.put(string + "Sup", "");
                if (index != keySet.size()) {
                    stringBuffer.append("##");
                }
//                if (keySet.size() == 1){
//                    stringBuffer.append("##");
//                }
            }

            index++;
        }
        if (hasUpTo20) {
            map = mapWith20;
        }
        return stringBuffer.toString();
    }


}
